package com.wateray.ipassbook.ui.view.contentPanel;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.apache.log4j.Logger;

import com.wateray.ipassbook.domain.Entity;
import com.wateray.ipassbook.domain.form.PassbookTradeForm;
import com.wateray.ipassbook.kernel.event.IPassbookEvent;
import com.wateray.ipassbook.kernel.event.IPassbookEventType;
import com.wateray.ipassbook.kernel.service.PassbookTradeService;
import com.wateray.ipassbook.ui.action.ActionManager;
import com.wateray.ipassbook.ui.action.AddTransferAction;
import com.wateray.ipassbook.ui.action.DeleteTransferAction;
import com.wateray.ipassbook.ui.action.ModifyTransferAction;
import com.wateray.ipassbook.ui.action.ShowAllRecorderAction;
import com.wateray.ipassbook.ui.action.ShowCurrentMonthRecordAction;
import com.wateray.ipassbook.ui.action.ShowCurrentYearRecordAction;
import com.wateray.ipassbook.ui.action.ShowDeleteReceiptAction;
import com.wateray.ipassbook.ui.action.ShowModifyReceiptAction;
import com.wateray.ipassbook.ui.action.ShowTodayRecordAction;
import com.wateray.ipassbook.ui.dialog.TransferDialog;
import com.wateray.ipassbook.ui.model.TransferTableModel;
import com.wateray.ipassbook.ui.widget.PopUpButton;
import com.wateray.ipassbook.util.CalendarUtils;
import com.wateray.ipassbook.util.LanguageLoader;
import com.wateray.ipassbook.util.log4j.Log;

/**
 * @author wateray
 * @create 2009-4-30
 */
public class TransferPage extends AbstractPage {

	/** serialVersionUID. */
	private static final long serialVersionUID = -6234121444094837341L;

	private static TransferPage thisPage = new TransferPage();
	private Logger logger = Log.getLogger(this.getClass());

	/** The addButton. */
	private JButton addButton;

	/** The modifyButton. */
	private JButton modifyButton;

	/** The deleteButton. */
	private JButton deleteButton;

	/** The dataFilterButton. */
	private PopUpButton dataFilterButton;

	/** dataFilterButton Group */
	private ButtonGroup dataFilterGroup;

	/** Button to show all records. */
	private JRadioButtonMenuItem allMenuItem;

	/** Button to show today's records. */
	private JRadioButtonMenuItem todayMenuItem;

	/** Button to show this month's records. */
	private JRadioButtonMenuItem monthMenuItem;

	/** Button to show this year's records. */
	private JRadioButtonMenuItem yearMenuItem;

	/** transferTable */
	private JTable transferTable;
	
	/** transferTableModel */
	private TransferTableModel dataModel;

	/** the Constructor */
	private TransferPage() {
		super();
	}

	/**
	 * @return an instance of the ReceiptPage.
	 * */
	public static TransferPage getInstance() {
		if (thisPage == null) {
			thisPage = new TransferPage();
		}

		return thisPage;
	}

	@Override
	protected Component getTopPane() {
		super.getTopPane();
		buttonBar.add(getAddButton());
		buttonBar.add(getModifyButton());
		buttonBar.add(getDeleteButton());
		buttonBar.add(getDataFilterButton());
		return buttonBar;
	}

	@Override
	protected Component getCenterPane() {
		return new JScrollPane(getTransferTable());
	}
	
	private JButton getAddButton() {
		if (addButton == null) {
			addButton = new JButton();
			AddTransferAction action = (AddTransferAction) ActionManager.getAction(AddTransferAction.class);
			//TEST
//			action.setData(getTransferTable());
			addButton.setAction(action);
			//TEST END
			
		}
		return addButton;
	}

	private JButton getModifyButton() {
		if (modifyButton == null) {
			modifyButton = new JButton();
			//TEST
			ModifyTransferAction action = (ModifyTransferAction) ActionManager.getAction(ModifyTransferAction.class);
			action.setData(getTransferTable());
//			action.setData(dataModel.getRowObject(getSelectRowIndex()));
			modifyButton.setAction(action);
			//TEST END
		}
		return modifyButton;
	}

	private JButton getDeleteButton() {
		if (deleteButton == null) {
			deleteButton = new JButton();
			//TEST
			DeleteTransferAction action = (DeleteTransferAction) ActionManager.getAction(DeleteTransferAction.class);
			action.setData(getTransferTable());
//			action.setData(dataModel.getRowObject(getSelectRowIndex()));
			deleteButton.setAction(action);
			//TEST END
		}
		return deleteButton;
	}

	private JButton getDataFilterButton() {
		if (dataFilterButton == null) {
			dataFilterButton = new PopUpButton(LanguageLoader
					.getString("Data_Filter"), PopUpButton.BOTTOM_RIGHT);

			allMenuItem = new JRadioButtonMenuItem(LanguageLoader.getString("All_Record"));
			allMenuItem.setActionCommand(LanguageLoader.getString("All_Record"));
			allMenuItem.addActionListener( new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					showData(CalendarUtils.getInstance());
				}
				
			});
			todayMenuItem = new JRadioButtonMenuItem(LanguageLoader.getString("Today"));
			todayMenuItem.setActionCommand(LanguageLoader.getString("Today"));
			todayMenuItem.addActionListener( new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					showData(CalendarUtils.getTodayInstance());
				}	
			});
			monthMenuItem = new JRadioButtonMenuItem(LanguageLoader.getString("Current_Month"));
			monthMenuItem.setActionCommand(LanguageLoader.getString("Current_Month"));
			monthMenuItem.addActionListener( new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					showData(CalendarUtils.getCurrentMonthInstance());
				}	
			});
			yearMenuItem = new JRadioButtonMenuItem(LanguageLoader.getString("Current_Year"));
			yearMenuItem.setActionCommand(LanguageLoader.getString("Current_Year"));
			yearMenuItem.addActionListener( new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					showData(CalendarUtils.getCurrentYearInstance());
				}	
			});

			dataFilterGroup = new ButtonGroup();
			dataFilterGroup.add(allMenuItem);
			dataFilterGroup.add(todayMenuItem);
			dataFilterGroup.add(monthMenuItem);
			dataFilterGroup.add(yearMenuItem);

			dataFilterButton.add(allMenuItem);
			dataFilterButton.add(new JSeparator());
			dataFilterButton.add(todayMenuItem);
			dataFilterButton.add(monthMenuItem);
			dataFilterButton.add(yearMenuItem);
			dataFilterButton.add(new JSeparator());

			allMenuItem.setSelected(true);
			showData(CalendarUtils.getInstance());

		}
		return dataFilterButton;
	}

	/**
	 * @return transferTable
	 * */
	public JTable getTransferTable() {
		if (transferTable == null) {
			transferTable = new JTable();
		    dataModel = new TransferTableModel(
					getColumnNames());
			transferTable.setModel(dataModel);
			transferTable.setPreferredScrollableViewportSize(new Dimension(500,
					70));
			transferTable.setFillsViewportHeight(true);

			transferTable.getSelectionModel().addListSelectionListener(
					new ListSelectionListener() {

						@Override
						public void valueChanged(ListSelectionEvent e) {
							// TODO Auto-generated method stub
							if (transferTable.getSelectedRow() != -1) {
								ActionManager.getAction(
										ModifyTransferAction.class)
										.setEnabled(true);
								ActionManager.getAction(
										DeleteTransferAction.class)
										.setEnabled(true);
							} else {
								ActionManager.getAction(
										ModifyTransferAction.class)
										.setEnabled(false);
								ActionManager.getAction(
										DeleteTransferAction.class)
										.setEnabled(false);
							}
						}
					});

			transferTable.setAutoCreateRowSorter(true);
			// set data.
			// showData(CalendarUtils.getCurrentMonthInstance());
			setCellEditor(transferTable);
		}

		return transferTable;
	}

	/***/
	private Vector<String> getColumnNames() {
		Vector<String> columnNames = new Vector<String>();
		columnNames.add(LanguageLoader.getString("No"));
		columnNames.add(LanguageLoader.getString("Date"));
		columnNames.add(LanguageLoader.getString("OutPassbook"));
		columnNames.add(LanguageLoader.getString("outAmount"));
		columnNames.add(LanguageLoader.getString("Rate"));
		columnNames.add(LanguageLoader.getString("InPassbook"));
		columnNames.add(LanguageLoader.getString("inAmount"));
		columnNames.add(LanguageLoader.getString("Memo"));

		return columnNames;
	}

	/***/
	private void setCellEditor(JTable table) {
		// Date
		// TableColumn column0 = table.getColumnModel().getColumn(0);
		// SubjectEntity
		// TableColumn columnSubject = table.getColumnModel().getColumn(2);
		// JComboBox subjectComboBox = new JComboBox();
		// SubjectComboBoxModel subjectComboBoxModel = new
		// SubjectComboBoxModel();
		// subjectComboBox.setModel(subjectComboBoxModel);
		// subjectComboBoxModel.setDefaultData(Constant.EXPENSE_KBN);
		// columnSubject.setCellEditor(new DefaultCellEditor(subjectComboBox));
		// subjectComboBox.setRenderer(new SubjectListCellRender());
		//
		// TableColumn columnPassbook = table.getColumnModel().getColumn(6);
		// JComboBox passbookComboBox = new JComboBox();
		// PassbookComboBoxModel2 passbookComboBoxModel = new
		// PassbookComboBoxModel2();
		// passbookComboBox.setModel(passbookComboBoxModel);
		// columnPassbook.setCellEditor(new
		// DefaultCellEditor(passbookComboBox));
		// passbookComboBox.setRenderer(new PassbookListCellRender());

		// memo
//		TableColumn columnMemo = table.getColumnModel().getColumn(7);
//		columnMemo.setCellRenderer(new MemoReceiptTableCellRenderer());
	}

	public void showData(CalendarUtils c) {
		((TransferTableModel) getTransferTable().getModel()).setData(getData(c
				.getBeginDay(), c.getEndDay()));

		if (dataFilterGroup.getSelection() != null) {
			dataFilterButton.setText(LanguageLoader.getString("Data_Filter")
					+ " [" + dataFilterGroup.getSelection().getActionCommand()
					+ "]");
		}
	}

	public Vector<Entity> getData(String beginDay, String endDay) {
		Vector<Entity> vect = new Vector<Entity>();
		PassbookTradeService service = new PassbookTradeService();
		List list = service.getPassbookTradeFormList(beginDay, endDay);
		Iterator it = list.iterator();
		while (it.hasNext()) {
			vect.add((Entity) it.next());
		}
		return vect;
	}

	// @Override
	// public String getPageName() {
	// // TODO Auto-generated method stub
	//             
	// return LanguageLoader.getString("Receipt");
	// }

	@Override
	public void disposePage() {
		// TODO Auto-generated method stub
		super.disposePage();
		thisPage = null;
	}

	@Override
	public void update(IPassbookEvent event) {
		// TODO Auto-generated method stub
		IPassbookEventType type = event.getEventType();
		dataModel = (TransferTableModel) transferTable.getModel();
		Object source = event.getSource();
		PassbookTradeForm form = null;
		if(source instanceof TransferDialog){
			form = ((TransferDialog)source).getData();
		}
		//update selected row.
		if(type.equals(IPassbookEventType.PassbookTableAddEvent)){
			//dataModel.addRow(rowData);
			if(form != null){
				dataModel.addRow(form);
			}
		}
		else if(type.equals(IPassbookEventType.PassbookTableModifyEvent)){
			if(form != null){
				dataModel.updateRow(getSelectRowIndex(), form);
			}
		}	
		else if(type.equals(IPassbookEventType.PassbookTableDELETEEvent)){
			dataModel.removeRow(getSelectRowIndex());
		}
		//else all the rows in view should be updated.
		
	}
	
	/**
	 * @return selected row's index.
	 * convertRowIndexToModel().
	 * */
	public int getSelectRowIndex(){
		return getTransferTable().convertRowIndexToModel(getTransferTable().getSelectedRow());
	}
}
